package com.xing.common.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bradish7Y on 2017/8/14.
 */
@Aspect
public class DynamicDataSourceAspect {

    private static Logger _log = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    private final ThreadLocal<Long> timeCost = new InheritableThreadLocal<>();
    private static List<Integer> timeThreshold = new ArrayList<>();

    @Pointcut("execution(* com.xing.dao..*.*(..))")
    public void pointcut() {

    }

    @Before("pointcut()")
    public void doBeforeInServiceLayer(JoinPoint joinPoint) {
        timeCost.set(System.currentTimeMillis());
    }

    @After("pointcut()")
    public void doAfterInServiceLayer(JoinPoint joinPoint) {
        long elapsedTime = System.currentTimeMillis() - timeCost.get();
    }

    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        //执行
        Object result = pjp.proceed();

        Signature signature = pjp.getSignature();
        String method = signature.getDeclaringTypeName() + "#" + signature.getName();

        long endTime;
        for (int threshold : timeThreshold) {
            endTime = System.currentTimeMillis() - startTime;
            if (endTime > threshold) {
                _log.warn("method:{}, gt {}ms, time elapsed:{}ms", method, threshold, endTime);
                break;
            }
        }

        return result;
    }
}
